package com.mls.guardian.remoting.netty;


import com.mls.guardian.protocol.RemoteCommand;
import com.mls.guardian.remoting.RemoteInvokeCallback;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * Created by jl on 15/9/10.
 */
public class ResponseFuture {
    private volatile RemoteCommand responseCommand;
    private volatile boolean sendRequestOK = true;
    private final long timeoutMillis;
    private final long defaultTimeoutMillis = 600000;
    private final long beginTimestamp = System.currentTimeMillis();
    private RemoteInvokeCallback callback;
    private final CountDownLatch countDownLatch = new CountDownLatch(1);
    private Throwable cause;
    // 保证回调的callback方法至多至少只被执行一次
    private final AtomicBoolean executeCallbackOnlyOnce = new AtomicBoolean(false);


    public ResponseFuture(long timeoutMillis){
        if(timeoutMillis == -1){
            this.timeoutMillis = defaultTimeoutMillis;
        }else{
            this.timeoutMillis = timeoutMillis;
        }

    }

    public boolean isTimeout() {
        long diff = System.currentTimeMillis() - this.beginTimestamp;
        return diff > this.timeoutMillis;
    }

    public long getBeginTimestamp() {
        return beginTimestamp;
    }

    public long getTimeoutMillis() {
        return timeoutMillis;
    }

    public RemoteCommand waitResponse(long timeoutMillis) throws InterruptedException {
        if(timeoutMillis == -1){
            timeoutMillis = defaultTimeoutMillis;
        }
        this.countDownLatch.await(timeoutMillis, TimeUnit.MILLISECONDS);

        return this.responseCommand;
    }


    public RemoteCommand waitResponse() throws InterruptedException {

        this.countDownLatch.await(timeoutMillis, TimeUnit.MILLISECONDS);

        return this.responseCommand;
    }


    public void putResponse(final RemoteCommand responseCommand) {
        this.responseCommand = responseCommand;
        this.countDownLatch.countDown();
    }

    public void setCause(Throwable cause) {
        this.cause = cause;
    }

    public void setSendRequestOK(boolean sendRequestOK) {
        this.sendRequestOK = sendRequestOK;
    }
    public boolean isSendRequestOk(){
        return this.sendRequestOK;

    }


    public Throwable getCause() {
        return cause;
    }


    public void executeInvokeCallback() {
        if (callback != null) {
            if (this.executeCallbackOnlyOnce.compareAndSet(false, true)) {
                callback.onCompelete(this);
            }
        }
    }
}
